import router from '@/router';

import { getUploadUrl } from '@/utils/env';
import { useAuthStore } from '@/store';
export default {
	/**
	 * 跳转
	 * @param name 路由名称
	 * @param params 参数
	 * @param tabBar 是否tabBar
	 * @param redirect 是否关闭当前页
	 */
	handleJump(name, params = {}, tabBar = false, redirect = false) {
		console.log(params);
		if (tabBar === true) {
			router.replaceAll({ name: name, params: params });
		} else {
			if (redirect === true) {
				router.replace({ name: name, params: params });
			} else {
				router.push({ name: name, params: params });
			}
		}
	},
	/**
	 * 返回上一页
	 * @param timeout
	 */
	goBack(timeout = 1000) {
		setTimeout(() => {
			router.back();
		}, timeout);
	},

	//富文本图片处理
	formatRichText(html) {
		let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			return match;
		});
		newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
			match = match
				.replace(/width:[^;]+;/gi, 'max-width:100%;')
				.replace(/width:[^;]+;/gi, 'max-width:100%;');
			return match;
		});
		newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		newContent = newContent.replace(
			/\<img/gi,
			'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"',
		);
		return newContent;
	},
	/**
	 * 轻提示
	 * @param {*} title
	 * @param {*} options
	 */
	toast(title, options = {}) {
		uni.showToast({
			title,
			duration: 1500,
			icon: 'none',
			mask: true,
			...options,
		});
	},
	downloadFile(url, fileName = '') {
		console.log(url);
		var downloadTask = uni.downloadFile({
			url: url, //仅为示例，并非真实接口地址。
			filePath: wx.env.USER_DATA_PATH + fileName ? '/' + fileName : '',
			success: (res) => {
				console.log(res);
				if (res.statusCode === 200) {
					console.log('下载成功');
				}
				uni.showModal({
					title: '提示',
					content: '文件已下载',
					cancelText: '转发微信',
					confirmText: '打开文件',
					success: function (result) {
						if (result.confirm) {
							uni.openDocument({
								filePath: res.filePath,
								showMenu: true,
								success: () => {
									console.log('成功打开');
								},
							});
						}
						if (result.cancel) {
							const deviceInfo = wx.getDeviceInfo();
							console.log(deviceInfo);
							if (deviceInfo.platform === 'windows' || deviceInfo.platform === 'mac') {
								// PC端代码
								wx.saveFileToDisk({
									filePath: res.filePath,
									success() {},
									fail() {},
								});
							} else {
								// 其他平台代码
								uni.shareFileMessage({
									filePath: res.filePath,
									success() {},
									fail: console.error,
								});
							}
						}
					},
				});
			},
			complete: () => {},
		});
		downloadTask.onProgressUpdate((res) => {
			console.log('下载进度' + res.progress);
			console.log('已经下载的数据长度' + res.totalBytesWritten);
			console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
		});
	},
	/**
	 * 选择图片、视频
	 * @param {*} count
	 * @param {*} mediaType
	 * @returns
	 */
	chooseMedia(count = 1, mediaType = 'image') {
		return new Promise((resolve, reject) => {
			uni.chooseMedia({
				mediaType: mediaType,
				count: count, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择
				success: (res) => {
					resolve(res.tempFiles);
				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	},
	/**
	 * 上传
	 * @param {*} url
	 * @returns
	 */
	uploadFile(url) {
		const uploadUrl = getUploadUrl();
		uni.showLoading({
			title: '上传中',
		});

		return new Promise((resolve, reject) => {
			const authStore = useAuthStore();
			uni.uploadFile({
				url: uploadUrl,
				filePath: url,
				name: 'file',
				header: { token: authStore.getToken },
				success: (res) => {
					const data = JSON.parse(res.data);
					if (data.code === 1) {
						uni.hideLoading();
						resolve(data.data);
					} else {
						uni.hideLoading();
						uni.showModal({
							title: '上传失败',
							content: data.msg,
						});
						reject(res);
					}
				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	},
};
